import paramiko
from stat import S_ISDIR as isdir
import os


# 通用下载
def DownloadSftp(RemoteHost: dict, LocalFilePath, RemoteFilePath):
    """
        RemoteHost格式示例
        RemoteHost = {
            "host": "192.168.201.155",
            "port": 22,
            "username": "root",
            "password": "root"
        }
    """
    try:
        transport = paramiko.Transport((RemoteHost["host"], RemoteHost["port"]))
        transport.connect(username=RemoteHost["username"], password=RemoteHost["password"])
        sftp = paramiko.SFTPClient.from_transport(transport)

        DownloadSftp_File(sftp, LocalFilePath, RemoteFilePath)

        transport.close()
    except Exception as e:
        print("DownloadSftp : 无法连接", type(e), e)


# 文件下载，一般搭配通用下载使用
def DownloadSftp_File(sftp, LocalFilePath: str, RemoteFilePath: str):
    LocalFilePath = LocalFilePath.replace("\\", "/")
    RemoteFilePath = RemoteFilePath.replace("\\", "/")

    RemoteDirs = sftp.stat(RemoteFilePath)

    if isdir(RemoteDirs.st_mode):
        return DownloadSftp_DIr(sftp, LocalFilePath, RemoteFilePath)
    else:
        # print("下载文件：" + RemoteFilePath)
        sftp.get(RemoteFilePath, LocalFilePath)


# 必须搭配文件下载使用
def DownloadSftp_DIr(sftp, LocalFilePath: str, RemoteRootPath: str):
    if not os.path.exists(LocalFilePath):
        os.makedirs(LocalFilePath)

    for remotefile in sftp.listdir(RemoteRootPath):
        newremotefile = os.path.join(RemoteRootPath, remotefile)
        newlocalfile = os.path.join(LocalFilePath, remotefile)
        DownloadSftp_File(sftp, newlocalfile, newremotefile)
